///  ex_safe.dart
///
///  description:  安全取值String类型

/// 字符串
extension StringExtension on String? {

  /// 不展示null
  String get noNull => exStr=='null'?'':exStr;

  /// String 空安全取值
  String get exStr => this ?? '';

  /// 获取安全浮点数值，默认值为0
  int get exInt   =>  exStr.isNotEmpty ? int.parse(this!) : 0;

  /// 获取安全浮点数值，默认值为0.00
  double get exDouble   =>  exStr.isNotEmpty ? double.parse(this!) : 0.00;

  /// 占位文本
  String placeholder(String? str) => this ?? str.exStr;
  /// 前缀文本
  String prefix(String? str) => this != null ? '${str.exStr}$this' : str.exStr;
  /// 后缀文本
  String suffix(String? str) => this != null ? '$this${str.exStr}' : str.exStr;

  /// 字符串取最大长度
  String truncate(int maxLength) {
    String value = exStr;
    return value.length > maxLength ? value.substring(0, maxLength):value;
  }

}

/// int类型
extension IntExtension on int? {
  /// int类型转String
  String get exStr => (this ?? '').toString();
  /// 获取安全浮点数值，默认值为0
  int get exInt   =>  this ?? 0;
  /// 获取安全浮点数值，默认值为0.00
  double get exDouble   =>  (this ?? 0.00).toDouble();
}

/// double 类型
extension DoubleExtension on double? {
  /// double类型转String
  String get exStr => (this ?? '').toString();
  /// 获取安全浮点数值，默认值为0.00
  double get exDouble   =>  this ?? 0.00;
  /// 获取安全整数值，默认值为0
  int get exInt  =>  (this ?? 0).toInt();
}

/// num 类型
extension NumExtension on num? {

  /// 获取安全整数值，默认值为0
  int get exInt  =>  (this ?? 0).toInt();
  /// num类型转String类型整数值
  String get exIntStr => exInt.toString();

  /// 获取安全浮点数值，默认值为0.00
  double get exDouble   =>  (this ?? 0.00).toDouble();
  /// num类型转String类型浮点数值
  String get exDoubleStr => exDouble.toString();

  /// 获取安全整数值，默认值为空字符串
  String get exStr {
    if (this != null) {
      if (this is int)  return exInt.toString();
      if (this is double) return exDouble.toString();
    }
    return '';
  }
}

/// map 取值
/// double doubleResult = map.safeValue<double>('doubleValue', defaultValue: 0.0);
extension SafeMapAccess on Map<String, dynamic> {
  // 安全取值
  T? safeValue<T>(String key, {T? defaultValue}) {
    final dynamic value = this[key];
    if (value == null) return defaultValue;
    if (value is T) return value;
    // 处理将 int 转换为 double
    if (T == double && value is int) return value.toDouble() as T;
    // 处理将 double 转换为 int
    if (T == int && value is double) return value.toInt() as T;
    // 非字符串类型转换为字符串
    if (T == String && value is! String) return value.toString() as T;
    // 处理将 List
    if (T == List && value is List) return value as T;
    return defaultValue;
  }
}
